<template>
<div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图-->
    <el-card class="box-card">
        <!--添加角色按钮-->
        <el-row>
            <el-col>
                <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
            </el-col>
        </el-row>
        <!--角色列表区域-->
        <el-table :data="rolesList" border stripe>
            <!--权限展开区域-->
            <el-table-column type="expand">
                <template v-slot="scope">
                    <!--一级权限-->
                    <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                        <el-col :span="5">
                            <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <el-col :span="19">
                            <!--二级权限-->
                            <el-row :class="[i2 === 0? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                <el-col :span="6">
                                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <!--三级权限-->
                                    <el-tag closable type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <!--角色信息-->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
            <el-table-column label="操作" width="290">
                <template v-slot="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showSetRoleDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRole(scope.row.id)">删除</el-button>
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)" @close="SetRightDialogClosed">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>

    <!--添加角色对话框-->
    <el-dialog
            title="提示"
            :visible.sync="addRoleDialogVisible"
            width="50%" @close="addRoleDialogClosed">
        <el-form :model="addRoleForm" :rules="RoleRules" ref="addRoleRef">
            <el-form-item prop="roleName" label="角色名称">
                <el-input v-model="addRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item prop="roleDesc" label="角色描述">
                <el-input v-model="addRoleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRole()">确 定</el-button>
        </span>
    </el-dialog>

    <!--编辑角色对话框-->
    <el-dialog
            title="提示"
            :visible.sync="setRoleDialogVisible"
            width="50%" @close="setRoleDialogClosed">
        <el-form :model="setRoleForm" :rules="RoleRules" ref="setRoleRef">
            <el-form-item prop="roleName" label="角色名称">
                <el-input v-model="setRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item prop="roleDesc" label="角色描述">
                <el-input v-model="setRoleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setRole()">确 定</el-button>
        </span>
    </el-dialog>
    <!--分配权限对话框-->
    <el-dialog
            title="提示"
            :visible.sync="SetRightdialogVisible"
            width="50%">
        <el-tree
            :data="rightsTree"
            show-checkbox
            default-expand-all
            :default-checked-keys="defKeys"
            node-key="id"
            ref="setRightsTreeRef"
            highlight-current
            :props="defaultProps"
            >
        </el-tree>
        <span slot="footer" class="dialog-footer">
    <el-button @click="SetRightdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRight">确 定</el-button>
  </span>
    </el-dialog>
</div>
</template>

<script>
    export default {
        name: "Roles",
        data(){
            return{
                rolesList:[],
                SetRightdialogVisible: false,
                setRoleDialogVisible:false,
                addRoleDialogVisible:false,
                rightsTree:[],
                defaultProps:{
                    children:'children',
                    label:'authName'
                },
                defKeys:[],
                roleId:'',
                setRoleForm:{
                    roleName:'',
                    roleDesc:''
                },
                RoleRules:{
                    roleName:[{required:true,message:'角色名不能为空',trigger:"blur"}],
                    roleDesc:[{required:true,message:'角色描述不能为空',trigger:"blur"}]
                },
                addRoleForm:{
                    roleName:'',
                    roleDesc:''
                }


            }
        },
        created() {
            this.getRolesList()
        },
        methods:{
            //获取角色列表
            async getRolesList(){
               const {data:res} = await this.$http.get('/roles')
                if(res.meta.status !== 200) return this.$message.error('获取角色列表失败')
                this.rolesList = res.data
                //console.log(this.rolesList)
            },
            //删除角色权限
            async removeRightById(role,rightId){
                const removeRightRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if(removeRightRes !== 'confirm') return this.$message.info("已取消操作")
                const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if(res.meta.status !==200 ) return this.$message.error("移除权限失败！")

                //不使用 this.getRolesList()，会发生页面的全部重新渲染
                role.children = res.data
                this.$message.success("移除权限成功！")
            },
            //获取当前id下的三级权限
             getleafKeys(node,arr){
                if(!node.children){
                    return arr.push(node.id)
                }
                node.children.forEach(item => {
                    this.getleafKeys(item,arr)
                })
            },
            //点击分配权限，获取权限数据
            async showSetRightDialog(role){
                this.roleId = role.id
                const {data:res}=await this.$http.get('rights/tree')
                if(res.meta.status!==200) return this.$message.error("获取权限失败！")
                this.rightsTree = res.data
                //console.log(this.rightsTree)
                this.getleafKeys(role,this.defKeys)
                //console.log(this.defKeys)
                this.SetRightdialogVisible = true
            },
            //每次关闭权限分配对话框，清空叶子节点
            SetRightDialogClosed(){
                this.defKeys=[]
            },
            //分配权限
            async allotRight(){
                const keys=[
                    ...this.$refs.setRightsTreeRef.getCheckedKeys(),
                    ...this.$refs.setRightsTreeRef.getHalfCheckedKeys()
                ]
                console.log(keys)
                const idStr = keys.join(',')
                const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
                if(res.meta.status!==200) return this.$message.error("分配权限失败！")
                this.$message.success("分配权限成功！")

                this.getRolesList()
                this.SetRightdialogVisible = false

            },

            //打开编辑角色对话框并渲染数据
            showSetRoleDialog(role){
                this.roleId = role.id
                this.setRoleForm.roleName = role.roleName
                this.setRoleForm.roleDesc = role.roleDesc
                this.setRoleDialogVisible = true
            },
            //编辑角色
            setRole(){
                this.$refs.setRoleRef.validate(async (valid)=>{
                    if(!valid) return
                    const {data:res} = await this.$http.put(`roles/${this.roleId}`,{
                        roleName:this.setRoleForm.roleName,
                        roleDesc:this.setRoleForm.roleDesc
                    })
                    console.log(this.setRoleForm)
                    console.log(res)
                    if (res.meta.status !== 200) return this.$message.error('编辑角色失败')
                    this.$message.success('编辑角色成功')
                    this.getRolesList()
                    this.setRoleDialogVisible = false
                })
            },
            //关闭编辑角色对话框
            setRoleDialogClosed(){
                this.roleId=''
            },
            //删除角色
            async removeRole(id){
                const removeRoleConfirm = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if(removeRoleConfirm !== 'confirm') return
                const {data:res} = await this.$http.delete('/roles/'+id)
                if(res.meta.status !== 200) return this.$message.error('删除角色失败')
                this.$message.success('编辑角色成功')
                this.getRolesList()
            },
            //打开添加角色对话框
            showAddRoleDialog(){
                this.addRoleDialogVisible = true
            },
            //关闭添加角色对话框
            addRoleDialogClosed(){
                this.$refs.addRoleRef.resetFields()
            },
            //添加角色
            addRole(){
                this.$refs.addRoleRef.validate(async (valid) => {
                    if(!valid) return this.$message.error('请填写角色信息')
                    const { data:res }=await this.$http.post('/roles',this.addRoleForm)
                    console.log(res)
                    if(res.meta.status !== 201) return this.$message.error('添加角色失败')
                    this.$message.success('添加角色成功')
                    this.getRolesList()
                    this.addRoleDialogVisible = false
                })
            }
        }
    }
</script>

<style lang="less" scoped>
    .bdtop {
        border-top: 1px solid #eeeeee;
    }
    .bdbottom {
        border-bottom: 1px solid #eeeeee;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
    .el-tag {
        margin: 5px;
    }
</style>
